﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Doan.Website.Models;
using Ext.Net;
using Ext.Net.MVC;
using System.Linq.Dynamic;

namespace Doan.Website.Controllers
{
    [DirectController]
    public class DocumentController : Controller
    {
        //Document
        private static DoAnWebsiteEntities db = new DoAnWebsiteEntities();

        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult ListDocument()
        {
            Session["includeInActiveDocument"] = false;
            Session["CharFilterDocument"] = "";
            return View();
        }

        public ActionResult IncludeInActive()
        {
            var store = X.GetCmp<Store>("DocumentStore");

            Session["includeInActiveDocument"] = !(bool)Session["includeInActiveDocument"];

            store.Reload();
            return this.Direct();
        }

        [DirectMethod]
        public ActionResult CharFilterDocument(string filterstring)
        {
            var store = X.GetCmp<Store>("DocumentStore");
            Session["CharFilterDocument"] = filterstring;
            store.Reload();
            return this.Direct();
        }

        public ActionResult BindingDocumentStore(StoreRequestParameters parameters)
        {
            var sampleData = (db.Documents.Join(db.DocumentTypes, tab1 => tab1.TypeId, tab2 => tab2.TypeId,
                                           (tab1, tab2) => new
                                           {
                                               tab1.DocumentId,
                                               tab1.Name,
                                               tab1.CreateDate,
                                               tab1.EffectiveDate,
                                               tab1.Info,
                                               tab2.DTName,
                                               tab1.Download,
                                               tab1.Active
                                           })
                             );


            bool includeInActive = (bool)Session["includeInActiveDocument"];
            string charFilter = (string)Session["CharFilterDocument"];

            var result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active)));
            if ("0".Equals(charFilter))
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) &&
                    (ent.Name.StartsWith("0") || ent.Name.StartsWith("1") ||
                    ent.Name.StartsWith("2") || ent.Name.StartsWith("3") ||
                    ent.Name.StartsWith("4") || ent.Name.StartsWith("5") ||
                    ent.Name.StartsWith("6") || ent.Name.StartsWith("7") ||
                    ent.Name.StartsWith("8") || ent.Name.StartsWith("9")
                    )));
            }

            else
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) && ent.Name.StartsWith(charFilter)));

            }

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.DocumentId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData.Select(ent => new { ent.DocumentId, ent.Name, ent.CreateDate, ent.EffectiveDate, ent.DTName, ent.Info, ent.Download, ent.Active }), result.Count());
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult CreateDocument()
        {
            ViewBag.HideTextBox = false;
            ViewBag.GDocumentId = new List<ListItem>();
            ViewBag.GDocumentId = db.DocumentTypes.ToList().Select(ent => new ListItem { Text = ent.DTName, Value = ent.TypeId.ToString() });
            ViewBag.CancerId = new List<ListItem>();
            ViewBag.CancerId = db.Cancers.ToList().Select(ent => new ListItem { Text = ent.CancerName, Value = ent.CancerId.ToString() });

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateDocument(Document model)
        {
            if (ModelState.IsValid)
            {
                var upFile = X.GetCmp<FileUploadField>("UpFile");
                if (upFile.HasFile)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//UploadFile//" +
                                                  httpPostedFileBase.FileName);
                        model.File = "/Content/UploadFile/" + httpPostedFileBase.FileName;
                    }
                }

                model.CreateDate = model.EffectiveDate = DateTime.Now;
                model.Active = true;
                model.Download = 0;
                db.AddToDocuments(model);
                db.SaveChanges();
                X.Msg.Notify("Thành công", "Tạo mới thành công!").Show();
                return this.FormPanel();
            }

            X.Msg.Notify("Lỗi", "Tạo mới không thành công!").Show();

            return this.FormPanel();
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult EditDocument(int id)
        {
            ViewBag.HideTextBox = false;
            ViewBag.GDocumentId = new List<ListItem>();
            ViewBag.GDocumentId = db.DocumentTypes.ToList().Select(ent => new ListItem { Text = ent.DTName, Value = ent.TypeId.ToString() });
            ViewBag.CancerId = new List<ListItem>();
            ViewBag.CancerId = db.Cancers.ToList().Select(ent => new ListItem { Text = ent.CancerName, Value = ent.CancerId.ToString() });

            Document document = db.Documents.Single(m => m.DocumentId == id);
            return View(document);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditDocument(Document model)
        {
            Document document1 = db.Documents.Single(c => c.DocumentId == model.DocumentId);
            if (ModelState.IsValid)
            {
                var upFile = X.GetCmp<FileUploadField>("upFile");
                if (upFile.HasFile)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//UploadFile//" +
                                                  httpPostedFileBase.FileName);
                        model.File = "/Content/UploadFile/" + httpPostedFileBase.FileName;
                    }
                }
                else
                {
                    model.File = document1.File;
                }

                model.CreateDate = document1.CreateDate;
                model.EffectiveDate = DateTime.Now;
                db.Documents.Detach(document1);
                db.Documents.Attach(model);
                db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Thành công", "Sửa thành công!").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Lỗi", "Sửa không thành công!").Show();
            return this.FormPanel();
        }

        [DirectMethod]
        public ActionResult DeleteDoc(int id)
        {
            var deleteItem = db.Documents.SingleOrDefault(x => x.DocumentId == id);
            db.Documents.DeleteObject(deleteItem);
            db.SaveChanges();
            var store = X.GetCmp<Store>("DocumentStore");
            store.Reload();
            return this.FormPanel();
        }
    }
}
